package com.xiaomaoguai.fcp.pre.kepler.trace.endpoint;

import com.xiaomaoguai.fcp.pre.kepler.trace.constants.KeplerTraceConstant;
import io.jaegertracing.internal.metrics.InMemoryMetricsFactory;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author August.Zhang
 * @version v1.0.0
 * @date 2020/1/17 15:55
 * @since JDK 1.8
 */
@Endpoint(id = "jaegerMetrics")
@ConditionalOnClass({Endpoint.class})
@ConditionalOnBean({InMemoryMetricsFactory.class})
@ConditionalOnProperty(value = KeplerTraceConstant.KEPLER_OPENTRACING_JAEGER_METRICS_ENABLED, havingValue = "true", matchIfMissing = true)
public class JaegerMetricsEndpoint {

	@Resource
	private InMemoryMetricsFactory metricsFactory;

	@ReadOperation
	public Map<String, Object> jaegerMetrics() throws Exception {
		Map<String, Object> result = new HashMap<>(4);
		String counters = "counters";
		String timers = "timers";
		String gauges = "gauges";

		Field countersField = FieldUtils.getDeclaredField(metricsFactory.getClass(), counters, true);
		result.put(counters, countersField.get(metricsFactory));

		Field timersField = FieldUtils.getDeclaredField(metricsFactory.getClass(), timers, true);
		result.put(timers, timersField.get(metricsFactory));

		Field gaugesField = FieldUtils.getDeclaredField(metricsFactory.getClass(), gauges, true);
		result.put(gauges, gaugesField.get(metricsFactory));
		return result;
	}

}
